#include "threadlistmodel.h"
#include "components/thread.h"
#include "components/post.h"
#include "log.h"

ThreadListModel::ThreadListModel(const Wishmaster::ThreadPtr& thread, QObject *parent) :
	ThreadModel(thread, parent)
{
	if(!thread.isNull())
		this->thread()->unswap();
}

int ThreadListModel::columnCount(const QModelIndex& parent) const
{
	Q_UNUSED(parent);
	return 1;
}

QModelIndex ThreadListModel::index(int row, int column, const QModelIndex& parent) const
{
	return hasIndex(row, column, parent) ? createIndex(row, column, 0) : QModelIndex();
}

int ThreadListModel::rowCount(const QModelIndex& parent) const
{
	Q_UNUSED(parent);
	if(!thread())
		return 0;
	return thread()->getActualPostsCount();
}

QVariant ThreadListModel::data(const QModelIndex& index, int role) const
{
	if(!thread())
		return QVariant();

	if(!index.isValid())
		return QVariant();

	Wishmaster::PostPtr post = thread()->getPost(index.row());
	if(!post)
		return QVariant();

	switch(role)
	{
	case Qt::DisplayRole:
		return post->text();

	case PostId:
		return uint(post->id().postId());

	case PosterName:
		return post->name();

	case PostSubject:
		return post->topic();

	case PostVisibility:
		return post->visibility();
	}

	if((role <= AttachmentBase) && (role >= MaxAttachment))
	{
		int attachIndex = role - AttachmentBase;
		if((attachIndex < 0) || (attachIndex >= post->attachmentCount()))
			return QVariant();
		Wishmaster::AttachmentPtr attach = post->attachment(attachIndex);
		if(attach->type().startsWith("image") && attach->hasData())
			return QVariant(attach->image());
	}

	if((role <= AttachmentThumbBase) && (role >= MaxAttachmentThumb))
	{
		int attachIndex = role - AttachmentThumbBase;
		if((attachIndex < 0) || (attachIndex >= post->attachmentCount()))
			return QVariant();
		Wishmaster::AttachmentPtr attach = post->attachment(attachIndex);
		if(attach->hasThumbnail())
			return QVariant(attach->thumbnail());
	}

	if((role < AttachmentLinkBase) && (role >= MaxAttachmentLink))
	{
		int attachIndex = role - AttachmentLinkBase;
		if((attachIndex < 0) || (attachIndex >= post->attachmentCount()))
			return QVariant();
		Wishmaster::AttachmentPtr attach = post->attachment(attachIndex);
		return QVariant(attach->thumbnailUrl());
	}

	if((role < AttachmentThumbLinkBase) && (role >= MaxAttachmentThumbLink))
	{
		int attachIndex = role - AttachmentThumbLinkBase;
		if((attachIndex < 0) || (attachIndex >= post->attachmentCount()))
			return QVariant();
		Wishmaster::AttachmentPtr attach = post->attachment(attachIndex);
		return QVariant(attach->url());
	}

	return QVariant();
}

QModelIndex ThreadListModel::parent(const QModelIndex &child) const
{
	Q_UNUSED(child);
	return QModelIndex();
}
